package com.lovegu.two;

import javafx.application.Application;
import javafx.stage.Stage;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 基于 JavaFx 实现文字聊天室-服务端
 * </p>
 *
 * @author 老顾
 * @since 2023/3/29
 */
public class ChatRoomServer {

    private final int port;
    private final Map<String, Socket> clientMap;

    public ChatRoomServer(int port) {
        this.port = port;
        this.clientMap = new HashMap<>();
    }

    public void start() {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务器已启动，端口号：" + port);

            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("客户端已连接：" + socket.getRemoteSocketAddress());

                // 接收客户端发送的用户名
                DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                String userName = inputStream.readUTF();
                clientMap.put(userName, socket);

                // 启动客户端处理线程
                ClientHandler clientHandler = new ClientHandler(socket, clientMap, userName);
                Thread clientThread = new Thread(clientHandler);
                clientThread.setDaemon(true);
                clientThread.start();
            }
        } catch (IOException e) {
            System.out.println("启动服务器失败");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ChatRoomServer server = new ChatRoomServer(8888);
        server.start();
    }

    private static class ClientHandler implements Runnable {
        private final Socket socket;
        private final Map<String, Socket> clientMap;
        private final String userName;

        public ClientHandler(Socket socket, Map<String, Socket> clientMap, String userName) {
            this.socket = socket;
            this.clientMap = clientMap;
            this.userName = userName;
        }

        @Override
        public void run() {
            try (DataInputStream inputStream = new DataInputStream(socket.getInputStream())) {
                while (true) {
                    String message = inputStream.readUTF();
                    System.out.println(userName + ": " + message);

                    // 向所有客户端转发消息
                    for (Map.Entry<String, Socket> entry : clientMap.entrySet()) {
                        String clientName = entry.getKey();
                        Socket clientSocket = entry.getValue();

                        if (!clientName.equals(userName)) {
                            try {
                                DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
                                outputStream.writeUTF(userName + ": " + message);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            } catch (IOException e) {
                System.out.println("客户端已断开：" + socket.getRemoteSocketAddress());
                clientMap.remove(userName);
            }
        }
    }
}